
    head.js(
        {jquery:         '/public/application/script/libraries/jquery-1.7.1.min.js'},
        {tools:          '/public/application/script/libraries/jquery.tools.min.js'},
        {livequery:      '/public/application/script/libraries/jquery.livequery.js'},
        {animate_colors: '/public/application/script/libraries/jquery.animate-colors-min.js'},
        {jqueryUI:       '/public/application/script/libraries/jquery-ui-1.8.16.custom.js'},
      //  {ui_core:        '/public/application/script/libraries/ui/jquery.ui.core.min.js'},
      //  {ui_widget:      '/public/application/script/libraries/ui/jquery.ui.widget.min.js'},
      //  {ui_mouse:       '/public/application/script/libraries/ui/jquery.ui.mouse.min.js'},   
      //  {ui_draggable:   '/public/application/script/libraries/ui/jquery.ui.draggable.min.js'},
      //  {mousewheel:     '/public/application/script/libraries/mousewheel.js'},
       // {gwave_scrool:   '/public/application/script/libraries/gwave-scroll-pane-0.1.js'},
      //  {easing: '/public/application/script/libraries/jquery.easing.1.3.js'},
      //  {mCustomScrollbar: '/public/application/script/libraries/jquery.mCustomScrollbar.js'},
      //  {overscroll:     '/public/application/script/libraries/jquery.overscroll.min.js'},
        {slimScroll:     '/public/application/script/libraries/slimScroll.min.js'},
        {notify:         '/public/application/script/libraries/jquery.notify.min.js'},
        {tipsy:          '/public/application/script/libraries/jquery.tipsy.js'},
        {asmselect:      '/public/application/script/libraries/jquery.asmselect.js'},
        {datepicker:     '/public/application/script/libraries/datepicker.js'},
        {colorpicker:    '/public/application/script/libraries/colorpicker.js'},
        {checkboxes:     '/public/application/script/libraries/checkboxes.js'},
        //{uploadify_lang: '/public/application/script/libraries/uploadify/uploadifyLang_en.js'},
        //{uploadify:      '/public/application/script/libraries/uploadify/jquery.uploadify.js'},
        {fileuploader:   '/public/application/script/libraries/fileuploader.js'},
        {textboxlist_growing_input:       '/public/application/script/libraries/textboxlist/GrowingInput.js'},
        {textboxlist:                     '/public/application/script/libraries/textboxlist/TextboxList.js'},
        {textboxlist_autocomplete:        '/public/application/script/libraries/textboxlist/TextboxList.Autocomplete.js'},
        {textboxlist_autocomplete_binary: '/public/application/script/libraries/textboxlist/TextboxList.Autocomplete.Binary.js'},
        {ellipsis:          '/public/application/script/libraries/jquery.dotdotdot-1.1.2.js'},
        
        // jCrop
        {jCrop:                 '/public/application/script/libraries/jquery.Jcrop.js'},

        // jtop
        {raphael:               '/public/application/script/libraries/desktop/raphael.js'},
        {jtop:                  '/public/application/script/libraries/desktop/jtop.js'},
        {jtopExtTween:          '/public/application/script/libraries/desktop/extensions/jtop.ext.tween.js'},
        {jtopItem:              '/public/application/script/libraries/desktop/modules/jtop.item.js'},
        {jtopPanel:             '/public/application/script/libraries/desktop/modules/jtop.panel.js'},
        {jtopLayers:            '/public/application/script/libraries/desktop/modules/jtop.layers.js'},
        {jtopContextMenu:       '/public/application/script/libraries/desktop/modules/jtop.contextmenu.js'},
        {jtopTooltip:           '/public/application/script/libraries/desktop/modules/jtop.tooltip.js'},
        {jtopCursorIndicator:   '/public/application/script/libraries/desktop/modules/jtop.cursorindicator.js'},
        
        // mydesk
        {hasher:                '/public/application/script/libraries/desktop/hasher.js'},
        {site:                  '/public/application/script/libraries/desktop/site.js'},
        {mydeskExt:             '/public/application/script/libraries/desktop/extensions/mydesk.ext.js'},
        {mainModules:           '/public/application/script/libraries/desktop/views/main.modules.js'},
        {desktop:               '/public/application/script/libraries/desktop/views/desktop.view.js'},
        {addElementView:        '/public/application/script/libraries/desktop/views/add.element.view.js'},
        {editElementView:       '/public/application/script/libraries/desktop/views/edit.element.view.js'},
        {removeItemPromptView:  '/public/application/script/libraries/desktop/views/remove.item.prompt.view.js'},
        {projectView:           '/public/application/script/libraries/desktop/views/project.view.js'},
        {projectShowView:       '/public/application/script/libraries/desktop/views/project.show.view.js'},
        {desktopEmbedView:      '/public/application/script/libraries/desktop/views/desktop.embed.view.js'},

        {searchView:        '/public/application/script/libraries/desktop/views/search.view.js'},
        {mainView:          '/public/application/script/libraries/desktop/views/main.view.js'},
        {mainLoginView:     '/public/application/script/libraries/desktop/views/main.login.view.js'},
        {profileView:       '/public/application/script/libraries/desktop/views/profile.view.js'},
        {createAccountView: '/public/application/script/libraries/desktop/views/create.account.view.js'},
        {settingsView:      '/public/application/script/libraries/desktop/views/settings.view.js'},
        {messagesView:      '/public/application/script/libraries/desktop/views/messages.view.js'},
        {contactView:       '/public/application/script/libraries/desktop/views/contact.view.js'},
        {staticView:        '/public/application/script/libraries/desktop/views/static.view.js'}
        );

    head.ready(function(){


/*
 *  JQuery serialize plugin (serializes any value of checkbox)
 */

(function ($) {

     $.fn.serialize = function (options) {
         return $.param(this.serializeArray(options));
     };

     $.fn.serializeArray = function (options) {
         var o = $.extend({
         checkboxesAsBools: false
     }, options || {});

     var rselectTextarea = /select|textarea/i;
     var rinput = /text|hidden|password|search/i;

     return this.map(function () {
         return this.elements ? $.makeArray(this.elements) : this;
     })
     .filter(function () {
         return this.name && !this.disabled &&
             (this.checked
             || (o.checkboxesAsBools && this.type === 'checkbox')
             || rselectTextarea.test(this.nodeName)
             || rinput.test(this.type));
         })
         .map(function (i, elem) {
             var val = $(this).val();
             return val == null ?
             null :
             $.isArray(val) ?
             $.map(val, function (val, i) {
                 return {name: elem.name, value: val};
             }) :
             {
                 name: elem.name,
                 value: (o.checkboxesAsBools && this.type === 'checkbox') ? //moar ternaries!
                        (this.checked ? 1 : 0) :
                        val
             };
         }).get();
     };

})(jQuery); 

/*
 * Ajax request provider
 */

var AjaxRequest = (function ($) {
     
    var loaderBox = $('#ajax_loader');

    return {
    
        ajax: function(settings, disableProgress) {
            
            var settings = $.extend({
            
                cache: true,
                url: '',
                type: 'post',
                dataType: '',
                data: null,
                success: function(data) {},
                showProgress: !disableProgress
            
            }, settings);
            
            var progessTimer = setTimeout(function() {
                settings.showProgress && loaderBox.fadeIn(300); 
            }, 200);
           
 
            $.ajax({
                cache: settings.cache,
                url: settings.url,
                type: settings.type,
                dataType: settings.dataType,
                data: settings.data,
                success: function(data) {
                    settings.showProgress && loaderBox.fadeOut(300);
                    clearTimeout(progessTimer);
                    
                    settings.success.call(this, data);
                }
            });
            
            return this;
        }
        
    }

})(jQuery);

/*
 * One abstract level for ajax action via form
 */

function formAjaxAction(element, onsuccess)
{
    
    var on_progres = 0;
    $('body').delegate(element, 'submit', function(event) {

        
        if(!on_progres)
        {
            on_progres = 1;
            var action = $(this).attr('action');
            var id =  $(this).attr('id');
            var form = $(this);
            
            AjaxRequest.ajax(
            {
                    url: action,
                    type: 'post',
                    dataType: 'json',
                    data: $(this).serialize({checkboxesAsBools: true}),
                    success: function(json)
                    {
                        $('input:text, input:password').css('border-color','#bebebe')
                        if(json.success == 'true')
                        {
                              $("#notification_container").notify("create", {
                              title: json.message,
                              text: json.description
                              });  
                              
                              //init specyfic action 
                              onsuccess(json,form);
                                                                                         
                        }
                        else
                        {    
                            //color field borders
                            var suffix = '';
                            var message = '';
                           
                            if((form.hasClass('experience_form') && id ) || (form.hasClass('education_form') && id))
                            {
                                suffix = '_' + id.substr(5); 
                            }
                          
                            jQuery.each(json.errors, function(index, item) 
                            {
                                if(index == '_external')
                                {
                                    jQuery.each(item, function(external_index, external_item)
                                    {
                                        $('#' + external_index + suffix).animate({borderColor: '#c00000'});
                                        message = message + external_item + '<br/>';
                                    });
                                } 
                                else 
                                { 
                                    $('#' + index + suffix).animate({borderColor: '#c00000'});
                                    message = message + item + '<br/>';
                                }
                                
                            });
                                                        
                            //display notification
                            $('#notification_container').notify('create','error-template', 
                            {
                                 title: json.message,
                                 text: message
                            },
                            {
                                custom:true
                                //expires: false
                            });                           
                        }
                        
                        on_progres = 0;
                    }
            });
        }
        
        event.preventDefault();
        
    });
    
}

function actionDialog(element, onsuccess)
{
        if(typeof(element) === 'undefined')
            return false;
	
	var el = element;
		
	$('body').delegate(element, 'click', function(event){
              
                
		var content = $(this).attr('rel').split('|');
		$('body').append('<section id="msg-prompt"  class="overlay msg-prompt">' + 
                                    '<header>'+ content[0] +'</header>' + 
                                    '<div id="msg-content">' + content[1] + '</div>' + 
                                    '<div id="msg-action"><a id="overlay_accept" class="button_blue">' + content[2] +'</a> <a id="overlay_cancel" class="button_grey">'+ content[3] +'</a></div>' +
                                 '</section>');
		var that = $(this);
                
		var overlay_message = $('#msg-prompt').overlay(
		{
			top: 210,
			mask: {color: '#000', loadSpeed: 400, opacity: 0.5},
			closeOnClick: false,
			load: true,
			onClose: function() {$('#msg-prompt').remove();}	
		});
		
		$('#overlay_accept').click( function(){
		
				overlay_message.overlay().close();
				onsuccess(that);
							
		});
		
		$('#overlay_cancel').click( function(){
				overlay_message.overlay().close();
		});	

               
		event.preventDefault();
		//return false;
	});
}




/*
 *  Activate switch login panel to fogoten panel
 *  
 */

function loginToRecover()
{
    var panel =  $('#main_page_forms div'); 
    var loginPanel = 1;
    
    panel.find('a').click(function()
    {
        if (loginPanel == 1)
        {
             panel.animate({top: "-164px"}, 500, function(){loginPanel = 0;} );
        }
        else
        {
             panel.animate({top: "0px"}, 500, function(){loginPanel = 1;} );
        }
       
    });
} // end switchLoginForgoten


/*
 *  Activate main page slider 
 */
function slider()
{
    var currentSlideNumber = 0;
    
    var navigationSlider = function(){
        
       var slideAmount = $('#main_page_navigation li').length; 
       var  currentSlide = $('#main_page_navigation li[class=active]');

       $('#main_page_content div[rel='+ currentSlideNumber +']').removeClass('active');
       currentSlide.removeClass('active');
       currentSlideNumber++;
       if (currentSlideNumber == slideAmount)
       {
           $('#main_page_navigation li:first').addClass('active');
           currentSlideNumber = 0; 
       }
      else
      {
             currentSlide.next('li').addClass('active');         
      }
       $('#main_page_content div[rel='+ currentSlideNumber +']').addClass('active');

    } //switchNavigationSlider
     
    var interval = setInterval(navigationSlider, 10000);
    
    $('#main_page_navigation li').click(function(){
        clearInterval(interval);
         $('#main_page_content div[rel='+ currentSlideNumber +']').removeClass('active');
         
        var currentAnchor = $('#main_page_navigation li[class=active]');
        currentAnchor.removeClass('active');
        currentAnchor = $(this);
        currentSlideNumber = currentAnchor.attr('rel');
        currentAnchor.addClass('active');
        $('#main_page_content div[rel='+ currentSlideNumber +']').addClass('active');
        interval = setInterval(navigationSlider, 10000);
    });
} // end slider

function userLinksInit()
{
     $('body').delegate('.list_main_container', 'mouseenter', function() {
         $(this).children('.list_user_link').show();
         
     });
     $('body').delegate('.list_main_container', 'mouseleave', function() {
         $(this).children('.list_user_link').hide();
         
     });
}

function loginFormInit()
{

    formAjaxAction('#login_form', function(json,form){
        
        setTimeout(function(){
             
             AjaxRequest.ajax({
                url: '/',
                dataType: 'json',
                success: function(json){
                    
                    $('body').fadeOut();
                    var content = json.content;
                    setTimeout(function(){
                  
                        $('body').html(content).fadeIn();
                        
                    },500);
                }});
        }, 1000);

    });
}

function registerAccountFormInit()
{
    formAjaxAction('#register_account_form', function(json,form){
         
             form.parent('div').animate({'margin-top': '-376px'}, 500);
             form.parent('div').parent('section').animate({'height':'470px'}, 500, function(){
                 $(this).css('height','auto');
             });

    });
    
    formAjaxAction('#register_account_form_2', function(json,form) {
        
        setTimeout(function() {
            $('body').fadeOut(500, function(){
            window.location = '/'    
            });
        }, 2000)
        
    });
    
    

}

function standardFormInit()
{
     formAjaxAction('.standard_form', function(json,form){});
}

function experienceEducationFormInit()
{
    formAjaxAction('.experience_form, .education_form', function(json,form){
         
         //speciffic action for ecperience and educatation
         if(json.action == 'add')
         {
            form.next('header').next('ul').append(json.content).children('li:last-child').css('display','none').slideDown();
         }
         else
         {
            form.closest('li').html(json.content);                                
         } //end speciffic action
    });
                          
}

function internalNavigation()
{
    var on_progres = 0;
    var content_container = $('#content > section');
    $('.internal_action').click(function(event)
    {
       var anchor = $(this);
       var action = anchor.attr('href');
       var old_content_height = content_container.innerHeight();
       var old_content = content_container.children('div');
       
       if (!$(this).children('div').hasClass('active') && !on_progres)
       {
           on_progres = 1;
           $('#content > aside .list_main_container').removeClass('active');
           $(this).children('div').addClass('active');


           AjaxRequest.ajax
           ({
                url: action,
                dataType: 'json',
                cache: false,
                success: function(json)
                {             
                    content_container.css({'height':old_content_height + 'px',
                                           'overflow':'hidden'});


                    var new_content = old_content.after(json.content).next('div');               
                    var new_content_height = new_content.innerHeight();
                    var animation_time = 700;
                    
                    //have to move somewere else this shit
                    uploadUserPhoto();
                    uploadUserWallpaper();
                    
                    old_content.children('.header_menu')
                               .css('position','relative')
                               .next('div')
                               .css('padding-top','0px');
                    
                    old_content.animate({'margin-top': '-' + old_content_height +'px'},animation_time,function()
                    {
                        $(this).remove();
                         subInternalNavigation();
                         messagePaginationNavigation()
                         messageSearch()

                    });
                    content_container.animate({'height':new_content_height + 'px'},animation_time,function()
                    {
                         $('#content > section').css('height','auto')
                                                .children('div')
                                                .children('.header_menu')
                                                .css('position','absolute')
                                                .next('div')
                                                .css('padding-top','47px');

                         on_progres = 0;
                    });        

                }

            });      
       }
       event.preventDefault();
    })
  
}

function subInternalNavigation()
{
    var on_progres = 0;
    var content_container = $('#content > section > div');
    var animation_time = 700;
    
    $('.header_menu a').click(function(event)
    {
        var anchor = $(this);
        var action = anchor.attr('href');
               
        var old_content = content_container.children('div');
        var old_content_height = old_content.innerHeight();
        
       if (!anchor.hasClass('active') && !on_progres)
       {
           on_progres = 1;
           $('.header_menu a').removeClass('active');
           anchor.addClass('active');
           
           AjaxRequest.ajax
           ({
                url: action,
                dataType: 'json',
                cache: false,
                success: function(json)
                { 
                     content_container.css({'height':old_content_height + 'px',
                                           'overflow':'hidden'});
                                       
                    var new_content = old_content.after(json.content).next('div');               
                    var new_content_height = new_content.innerHeight();

                    //have to move somewere else this shit
                    uploadUserPhoto();

                    old_content.animate({'margin-top': -old_content_height + 47 +'px'},animation_time,function()
                    {
                        content_container.children('.header_menu')
                                   .css('position','absolute');
                        $(this).remove();
                    });
                    
                    content_container.animate({'height': new_content_height + 47 + 'px'},animation_time,function()
                    {
                         $('#content > section > div').css('height','auto')
                                                      .children('div')
                                                      .css('padding-top','47px');
                         on_progres = 0;
                    });  
                    
                }
            });
       }
        event.preventDefault();
    });
    
}

function messagePaginationNavigation()
{
    var on_progres = 0;
    var content_container = $('#content > section > div');
    var animation_time = 700;
    
    $('.pagination > .button_header').click(function(event)
    {
        
        var anchor = $(this);
        var action = anchor.attr('href');
        var header = anchor.parents('header');
               
        var old_content = content_container.children('div');
        var old_content_height = old_content.innerHeight();
        
       if (!on_progres)
       {
           on_progres = 1;
           
           AjaxRequest.ajax
           ({
                url: action,
                dataType: 'json',
                type: 'post',
                data: {internal_pagination: 1},
                cache: false,
                success: function(json)
                { 
                    content_container.css({'height':old_content_height + 47 + 'px',
                                           'overflow':'hidden'});
                                       
                     $('.pagination').remove();
                     header.append(json.pagination);
                      $('.pagination > .button_header').click(function(event){event.preventDefault()});    
     

                    var new_content = old_content.after(json.content).next('div');               
                    var new_content_height = new_content.innerHeight();


                    old_content.animate({'margin-top': -old_content_height +'px'},animation_time,function()
                    {
                        $(this).remove();
                        
                    });
                    
                    content_container.animate({'height': new_content_height + 47 + 'px'},animation_time,function()
                    {
                         $('#content > section > div').css('height','auto');
                        
                         messagePaginationNavigation();
                         on_progres = 0;
                         
                        
                    });  
                    
                }
            });
       }
        event.preventDefault();
    });
}

function messageSearch()
{
    var on_progres = 0;
    var content_container = $('#content > section > div');
    var animation_time = 700;
    
    $('#message_search_form').submit(function(event) {
           
        var action = $(this).attr('action');    
        var header = $(this).parents('header');
               
        var old_content = content_container.children('div');
        var old_content_height = old_content.innerHeight();

        if (!on_progres)
        {
            on_progres = 1;

            AjaxRequest.ajax
            ({
                url: action,
                dataType: 'json',
                type: 'get',
                data:  $(this).serialize({checkboxesAsBools: true}),
                cache: false,
                success: function(json)
                { 
                    content_container.css({'height':old_content_height + 47 + 'px',
                                           'overflow':'hidden'});

                     $('.pagination').remove();
                     header.append(json.pagination);
                     $('.pagination > .button_header').click(function(event){event.preventDefault()});    

                    var new_content = old_content.after(json.content).next('div');               
                    var new_content_height = new_content.innerHeight();

                    old_content.animate({'margin-top': -old_content_height +'px'},animation_time,function()
                    {
                        $(this).remove();

                    });

                    content_container.animate({'height': new_content_height + 47 + 'px'},animation_time,function()
                    {
                         $('#content > section > div').css('height','auto');

                         messagePaginationNavigation();
                         on_progres = 0;


                    });  

                }
            });
        }

        
        event.preventDefault();
    });
}


function messageSlider()
{

    $('#content').delegate('#content > section ul > li .message_link', 'click', function(event) {
    
      event.preventDefault();
      var action = $(this).attr('href');  
      var container = $(this).parents('.list_main_container');
      
      
        if (container.hasClass('unread'))
        {
            AjaxRequest.ajax
            ({
                url: action,
                dataType: 'json',
                cache: false,
                success: function(json)
                { 
                    container.removeClass('unread')
                }
            });
        }
        
        var all_message_link = $('#content > section ul > li .message_link');
        var all_active = all_message_link.parents('.active');          
        all_active.next('div').hide();
        
        if (container.hasClass('active'))
          {
            container.next('div').hide(function()
            {
                container.removeClass('active');
            });
        }
        else
        {
            all_active.removeClass('active')
            container.addClass('active').next('div').show();
        } 
                  
    });

}

function actionTipsy()
{
    $('.tooltip').livequery(function(){
        $(this).tipsy({gravity:'se'});
    });
}

function inputTipsyInit()
{
     var direction = 'w';
     
     if($(window).width() < 1260) {
         direction = 's';
     } 

     
     $('input').livequery(function(){
         $(this).tipsy({gravity: direction,trigger: 'focus'});
     });
     $('textarea').livequery(function(){
         $(this).tipsy({gravity: direction,trigger: 'focus'});
     })
}


function actionDelete()
{   
    actionDialog('.delete', function(that) {

        var anchor = that;
        var action = anchor.attr('href');
        
        AjaxRequest.ajax({
            url: action,
            dataType: 'json',
            success: function(json) {
                anchor.parents('li').slideUp().remove();
               }
        })
    });   
}

function actionEdit()
{  
     $('#content').delegate('.edit', 'click', function(event) {

        var all_edit_action = $('.edit');
        var anchor = $(this);
        var container = anchor.parent().parent();
        
        if (container.hasClass('active'))
        {
            container.next('form').slideUp(500, function()
            {
                container.removeClass('active');
            });
       }
       else
       {
           var all_active = all_edit_action.parents('.active');          
           all_active.next('form').slideUp(500,function(){all_active.removeClass('active')});
                     
           container.addClass('active').next('form').slideDown(500);  
       
       } 
 
        event.preventDefault();
    });
}

function actionPendingRequest()
{
      $('body, #invitation_box').delegate('.pending_request', 'click', function(event) {
        
        var anchor = $(this);
        var action = anchor.attr('href');
        
        AjaxRequest.ajax({
            url: action,
            dataType: 'json',
            success: function(json) {
                        anchor.parents('li').slideUp();
                         $("#notification_container").notify("create", {
                            title: json.message,
                            text: 'This is an example of the default config, and will fade out after five seconds.'
                         });  
                    }
                });
      
        event.preventDefault();
      });
}

function inputDateInit()
{
    
    $('#birth_date').livequery(function()
    {
        $('.datepicker').remove();
        $(this).DatePicker(
        {      
            date: $('#birth_date').val(),
            current: $('#birth_date').val(),
            position: 'right',
            eventName: 'focus',

            onChange: function(formated, dates){
                    $('#birth_date').val(formated);

                    }
        });
    });
}

function inputScreenSettingsInit()
{
    
    $('#color').livequery(function()
    {
        $('.colorpicker').remove();
        $(this).ColorPicker(
            {
                eventName: 'focus',


                onSubmit:  function(hsb, hex, rgb, el) {
                        $(el).val(hex);
                        $('#screen_color').animate({backgroundColor: '#' + hex});
                        $(el).ColorPickerHide();
                },
                onBeforeShow: function () {
                        $(this).ColorPickerSetColor(this.value);
                }
            }); 
    });
    
    $('#content').delegate('#grid', 'change', function() {

       if($(this).is(':checked'))
       {
           $('#screen_grid').fadeIn();
       }
       else
       {
           $('#screen_grid').fadeOut(); 
       }
    });
}

function checkboxesInit()
{
     $('.switch').livequery(function(){
        var message = $(this).attr('data-content').split('|');
        $(this).iphoneStyle({checkedLabel: message[0], //$(this).attr('data-switch-on') , 
                             uncheckedLabel: message[1], //$(this).attr('data-switch-off'), 
                             resizeContainer: false, 
                             resizeHandle: false});
    })
   // $('#content input:checkbox , textarea').livequery(function(){
   //     $(this).iphoneStyle({checkedLabel: 'Yes', uncheckedLabel: 'No', resizeContainer: false, resizeHandle: false});
   // })
}

function templateNotificationInit()
{
    $('#notification_container').remove();
    var template = '<div id="notification_container">' + 
                        '<div id="basic-template">' +
                            '<a class="ui-notify-cross ui-notify-close" href="#">x</a>' +
                            '<h1>#{title}</h1>' +
                            '<p>#{text}</p>' +
                        '</div>' +
                    
                        '<div id="error-template" class="error_notification">' +
                            '<a class="ui-notify-cross ui-notify-close" href="#">x</a>' +
                            '<span class="ui-icon ui-notify-alert"></span>' +
                            '<h1>#{title}</h1>' +
                            '<p>#{text}</p>' +
                        '</div>' +
                    '</div>';
      
    $(template).appendTo('body');
    $('#notification_container').notify({close: function(){$(this).remove()}});
}




function stillInit()
{
    $('#content').delegate('.still:checkbox', 'change', function() {

       if($(this).is(':checked'))
       {
           $(this).closest('li').prev('li').slideUp();
       }
       else
       {
           $(this).closest('li').prev('li').slideDown();
       }
    });
}

function multiselectInit()
{
    $('#field').livequery(function(){
        $(this).asmSelect(
        {
            sortable: false,
            animate: true,
            removeLabel: '',
            selectClass: 'standard_select_form',
            addItemTarget: 'top'
        });
    });
}


function toggleBoxesInit()
{
    var boxes = [{'anchor'   : '#message_icon_mini',
                  'box'      : '#message_box'},
              
                 {'anchor'   : '#search_icon',
                  'box'      : '#search_box'},
                 
                 {'anchor'   : '#message_icon',
                  'box'      : '#inbox_box',
                  'onToggle' : function(){
                               
                               if($('#inbox_box .toggle_loader').length){
                                   AjaxRequest.ajax({   
                                   url: '/message/get_toggle',
                                   dataType: 'json',
                                   success: function(json) {
                                            $('#inbox_box .list').html(json.content);
                                            $('#message_icon > .toolbar_notice').fadeOut();
                                            }},true);
                                  
                                   }
                              
                                }},
              
                 {'anchor'   : '#contact_icon',
                  'box'      : '#invitation_box',
                  'onToggle' : function(){
                               
                               if($('#invitation_box .toggle_loader').length){
                                   AjaxRequest.ajax({   
                                   url: '/contact/get_toggle',
                                   dataType: 'json',
                                   success: function(json) {
                                            $('#invitation_box .list').html(json.content);
                                            $('#contact_icon > .toolbar_notice').fadeOut();
                                            }},true);
                                  
                                   }
                              
                                }},
                 {'anchor'   : '#notification_icon',
                  'box'      : '#notification_box',
                  'onToggle' : function(){
                               
                               if($('#notification_box .toggle_loader').length){
                                   AjaxRequest.ajax({   
                                   url: '/notification/get_toggle',
                                   dataType: 'json',
                                   success: function(json) {
                                            $('#notification_box .list').html(json.content);              
                                            $('#notification_icon > .toolbar_notice').fadeOut();
                                            
                                            }},true);
                                            
                                           
                                   }
                              
                                }}]
          
    var temp = {};
     
    //helper function to bind toggle action on boxes
    var actionToggle = function(anchor, box, onComplete) {
          
        $(box).click(function(event){
            event.stopPropagation();
        });
        
        $('body').delegate(anchor, 'click', function(event) {
            
            $(box).toggle();
            
            
            
            if ($(this).hasClass('active')) {
                $(this).removeClass('active');
            } else {
               
                for (var i in boxes)
                {
                    temp = boxes[i];
                    if(anchor != temp.anchor)
                    {
                        hideBox(temp.anchor,temp.box);
                    }
                    else
                    {
                        if (temp.onToggle) {
                           temp.onToggle();
                           
                        }  
                    }
                }
                
                $(this).addClass('active');
            }
            event.stopPropagation();
            event.preventDefault();
        });
    }
  
   //helper function to hide boxes  
   var hideBox = function(anchor,box){
        if ($(anchor).hasClass('active')) {
                $(anchor).removeClass('active');
                $(box).hide();
        }}
    
    
    //bind action to hide elements if clicked on different area
    $('html').click(function() {
        //Hide the toggle boxes if visible
           
         for (var i in boxes)
         {
             temp = boxes[i]
             hideBox(temp.anchor,temp.box); 
         }
               
    }); 
    
    //bind action toggle to each box

    for (var i in boxes)
    {
      if(boxes.hasOwnProperty(i)) {
            temp = boxes[i]
            actionToggle(temp.anchor,temp.box); 
      }
    }
}




function uploadUserPhoto()
{ /*
    var start = document.cookie.indexOf("session=");
    var end = document.cookie.indexOf(";", start); // First ; after start
    if (end == -1) end = document.cookie.length; // failed indexOf = -1
    var cookie = document.cookie.substring(start + 8, end);

    $('#user_photo').uploadify({ 
            'langFile' : '/public/application/script/libraries/uploadify/uploadifyLang_en.js', // default uploadifyLang_en.js
            'swf' : '/public/application/script/libraries/uploadify/uploadify.swf', // default 
            'uploader' : '/settings/upload_photo', // default 
            'checkExisting' : '/settings/upload_check',
            'multi' : false,
            'cancelImage': '/public/application/images/icon_cross.png',
            'height': 25,
            'auto' : true,
            'fileSizeLimit' : 2*1024*1024,
            'postData'     : {'session': cookie},
            'fileObjName'     : 'user_photo',
            
            'onUploadSuccess': function(file, data, response){
                               var obj = jQuery.parseJSON(data);
                               if(obj.success !== 'true'){
                                   $('#' + file.id).addClass('uploadifyError');
                                   $('#' + file.id).find('.data').html(' - ' + obj.message);
                               } else {
                                   $('.profile_image').css('background-image','url(' + obj.message + ')')
                                                      .children('a').css('display','block');
                               }
            }
                         
         }); */
        if(!document.getElementById('user_photo'))
        return;
    
        var uploader = new qq.FileUploader({
                                    element: document.getElementById('user_photo'),
                                    action: '/settings/upload_user_photo',
                                    name: 'user_photo',
                                    allowedExtensions: ['png','jpg','jpeg'],        
                                    sizeLimit: 2*1024*1024,
                                    multiple: false,
                                    onComplete: function(id, fileName, responseJSON){

                                         if(responseJSON.success === true){
                                             var oldImage = $('#user_photo_container > img');
                                             $('#user_photo_container').prepend('<img src="' + responseJSON.message + '" alt="" />')
                                             oldImage.fadeOut(1000,function(){$(this).remove()}).next('a').css('display','block');
                                         }
                                    }
                        });
   
    
}

function uploadUserWallpaper()
{ /*
    var start = document.cookie.indexOf("session=");
    var end = document.cookie.indexOf(";", start); // First ; after start
    if (end == -1) end = document.cookie.length; // failed indexOf = -1
    var cookie = document.cookie.substring(start + 8, end);

    $('#user_wallpaper').uploadify({ 
            'langFile' : '/public/application/script/libraries/uploadify/uploadifyLang_en.js', // default uploadifyLang_en.js
            'swf' : '/public/application/script/libraries/uploadify/uploadify.swf', // default 
            'uploader' : '/settings/upload_wallpaper', // default 
            'checkExisting' : '/settings/upload_check',
            'multi' : false,
            'cancelImage': '/public/application/images/icon_cross.png',
            'height': 25,
            'auto' : true,
            'fileSizeLimit' : 4*1024*1024,
            'postData'     : {'session': cookie},
            'fileObjName'     : 'user_wallpaper',
            'progressData'       : 'speed', // 'percentage','speed','all - default'
            
            'onUploadSuccess': function(file, data, response){
                               var obj = jQuery.parseJSON(data);
                               if(obj.success !== 'true'){
                                   $('#' + file.id).addClass('uploadifyError');
                                   $('#' + file.id).find('.data').html(' - ' + obj.message);
                               } else {
                                   $('#screen_wallpaper').css('background','url(' + obj.message +') no-repeat')
                                                         .children('a').css('display','block');
                                   
                               }
            }
                         
         }); */
    
    if(!document.getElementById('user_wallpaper'))
        return;
    
    var uploader = new qq.FileUploader({
                                    element: document.getElementById('user_wallpaper'),
                                    action: '/settings/upload_wallpaper',
                                    name: 'user_wallpaper',
                                    allowedExtensions: ['png','jpg','jpeg'],        
                                    sizeLimit: 2*1024*1024,
                                    multiple: false,
                                    onComplete: function(id, fileName, responseJSON){

                                         if(responseJSON.success === true){
                                          
                                             var oldImage = $('#screen_wallpaper > img');
                                             if (oldImage.size()){
                                                $('#screen_wallpaper').prepend('<img src="' + responseJSON.message + '" alt="" />')
                                             } else {
                                                 $('#screen_wallpaper').prepend('<img src="' + responseJSON.message + '"  style="display: none" alt="" />').children('img').fadeIn(3000); 
                                             }
                                             
                                             oldImage.fadeOut(1000,function(){$(this).remove()});
                                             $('#delete_user_wallpaper').css('display','block');
                                   
                                         }
                                    }
                        });
   // $('#user_wallpaper').
}

function createAccountInit()
{
    $('#content').delegate('#currently', 'change', function(event){
       
        var select = $(this);
        $('#experience_form').hide();
        $('#education_form').hide();
        $('#else_form').hide();      
      
            switch (select.val()) {
                case '0':
                    $('#experience_form').show();

                    break;
                case '1':
                    $('#education_form').show();

                    break;
                case '2':
                    $('#else_form').show();

                    break;
            }
 
    });
}

function deleteUserPhotoInit()
{
    $('#content').delegate('#delete_user_photo', 'click', function(event){
        var button = $(this);
        var photo =  $(this).prevAll('img');
        var action = $(this).attr('href');
        
        AjaxRequest.ajax({
                url: action,
                dataType: 'json',
                success: function(json){
                    $('#user_photo_container').prepend('<img src="/public/application/images/default_profile_image.png" alt="" />')
                    photo.fadeOut(2000, function(){$(this).remove()});
                    button.css('display','none');
                }
        });
        event.preventDefault();
    })
       
}

function deleteUserWallpaperInit()
{
    $('#content').delegate('#delete_user_wallpaper', 'click', function(event){
        var button = $(this);
        var wallpaper =  $(this).prevAll('img');
        var action = $(this).attr('href');
        
        AjaxRequest.ajax({
                url: action,
                dataType: 'json',
                success: function(json){
                    wallpaper.fadeOut(2000, function(){$(this).remove()});
                    button.css('display','none');

                }
        });
        event.preventDefault();
    })
}

function actionAddFriendInit()
{
     actionDialog('#friend_icon_mini, .add_to_contacts', function(that) {
        
        var anchor = that;
        var action = anchor.attr('href');
        
         AjaxRequest.ajax({
                url: action,
                dataType: 'json',
                success: function(json) {

                             $("#notification_container").notify("create", {
                                title: json.message,
                                text: 'This is an example of the default config, and will fade out after five seconds.'
                             }); 
                             anchor.parent('li').slideUp();
                        }
                    });
      
        
    })
}

// function scrollInit()
// {
//     /*
//     var contact_list = $('#mini_contact_list')
//     if (contact_list.children('li').size() > 10)
//     {
//         contact_list.gWaveScrollPane();
        

//     } */
    
//     // $("#contact_list_container").mCustomScrollbar("vertical",400,"easeOutCirc",1.05,"auto","yes","yes",10);
//     //  $("#mini_contact_list").overscroll({direction: 'vertical', 
//     //                                      cursor: 'default'});
  
//     var contact_list = $('#mini_contact_list > ul')
//     if (contact_list.children('li').size() > 7)
//     {
//         $("#mini_contact_list").slimScroll({height: '329px', right: '0px', 'z-index': 1});
//     }
                                                           
// }

function autosuggestContactsInit() 
{
     $('#recipient').livequery(function(){
         textboxlist = new $.TextboxList('#recipient', {unique: true, plugins: {autocomplete: {
                     minLength: 1,
                     method: 'binary',
                     placeholder: $(this).attr('data-suggestion'),
                     onlyFromValues: true
         }}});
					
				             
         AjaxRequest.ajax({url: '/contact/get_contacts', 
                  dataType: 'json', 
                  success: function(json){
                            textboxlist.plugins['autocomplete'].setValues(json);
          
                            }     
                
                },true);
     
     });
}

function autosuggestLocalityInit()
{
        $('#address').livequery(function(){
         textboxlist = new $.TextboxList('#address', {unique: true, max: 1, plugins: {autocomplete: {
                     minLength: 3,
                     queryRemote: true,
                     placeholder: $(this).attr('data-suggestion'),
                     remote: {url: '/settings/get_locality'}
                    }}});
            
        });
}

function ellipsisInit()
{
     $('.ellipsis_word').livequery(function(){
          $(this).dotdotdot({
               ellipsis: ' ...',   //  The HTML to add as ellipsis.
               watch   : true    //  Whether to update the ellipsis:  true/'window'
          });
     });
     
     $('.ellipsis_character').livequery(function(){
          $(this).dotdotdot({
               ellipsis: ' ...',   //  The HTML to add as ellipsis.
               wrap    : 'letter',
               watch   : true    //  Whether to update the ellipsis:  true/'window'
          });
         
     });  
     
}

function noticeInit()
{
 
 var temp_amount_new_messages = '0';
 var temp_amount_new_invitations = '0';
 var temp_amount_new_notifications = '0';
 
 var noticeRequest = function(){
                          
                          AjaxRequest.ajax({
                            type: "post",
                            dataType: 'json',
                            url: '/notice',
                            data: {'amount_new_messages' : temp_amount_new_messages,
                                    'amount_new_invitations' : temp_amount_new_invitations,
                                    'amount_new_notifications' : temp_amount_new_notifications
                            },

                            async: true,
                            cache: false,
                            success: function (json) {
                              
                               if (temp_amount_new_messages != json.amount_new_messages && json.amount_new_messages != '0'){
                                   $('#message_icon .toolbar_notice').html(json.amount_new_messages).css('display','inline');
                               }
                               
                               if (temp_amount_new_invitations != json.amount_new_invitations && json.amount_new_invitations != '0'){
                                   $('#contact_icon .toolbar_notice').html(json.amount_new_invitations).css('display','inline');
                               }
                               
                               if (temp_amount_new_notifications != json.amount_new_notifications && json.amount_new_notifications != '0'){
                                   $('#notification_icon .toolbar_notice').html(json.amount_new_notifications).css('display','inline');
                               }
                               
                               temp_amount_new_messages = json.amount_new_messages;
                               temp_amount_new_invitations = json.amount_new_invitations;
                               temp_amount_new_notifications = json.amount_new_notifications
                                                   
                            }
                          },true);
                          
                    }   
     setInterval(noticeRequest,60000);
}

function fixedProjectHeaderInit()
{
    var top = 0
    
    if ($(window).scrollTop() > 35){
            
                $('#project_header').css({'top':'25px'});
                                      
             }
             else {
                 top = 60 - $(window).scrollTop();
                 $('#project_header').css({'top': top + 'px'});
             }
   
     $(window).scroll(function () {
      
         if ($(this).scrollTop() > 35){
            
                $('#project_header').css({'top':'26px',
                                          'box-shadow':'0px 5px 8px -4px #000',
                                          '-moz-box-shadow':'0px 5px 8px -4px #000',
                                          '-webkit-box-shadow':'0px 5px 8px -4px #000'});
                                      
             }
             else {
                 top = 60 - $(this).scrollTop();
                 $('#project_header').css({'top': top + 'px',
                                           'box-shadow':'none',
                                           '-moz-box-shadow':'none',
                                           '-webkit-box-shadow':'none'});
             }
             
    });
}

function mainPageAnimation()
{
    if($('#main_page_desktop').length > 0) {
    var icons = ['/public/application/images/48/blueprint sticky.png',
                 '/public/application/images/48/blueprint tool.png',
                 '/public/application/images/48/cd.png',
                 '/public/application/images/48/contact.png',
                 '/public/application/images/48/db.png',
                 '/public/application/images/48/injection.png',
                 '/public/application/images/48/mail.png',
                 '/public/application/images/48/mic.png',
                 '/public/application/images/48/note.png',
                 '/public/application/images/48/rssorange.png',
                 '/public/application/images/48/twitter.png',
                 '/public/application/images/48/111.png',
                 '/public/application/images/48/112.png',
                 '/public/application/images/48/113.png',
                 '/public/application/images/48/114.png',
                 '/public/application/images/48/115.png',
                 '/public/application/images/48/116.png',
                 '/public/application/images/48/117.png',
                 '/public/application/images/48/118.png',
                 '/public/application/images/48/119.png',
                  '/public/application/images/48/1.png',
                 '/public/application/images/48/2.png',
                 '/public/application/images/48/3.png',
                 '/public/application/images/48/4.png',
                 '/public/application/images/48/5.png',
                 '/public/application/images/48/6.png',
                 '/public/application/images/48/7.png',
                 '/public/application/images/48/8.png',
                 '/public/application/images/48/9.png',
                 '/public/application/images/48/105.png'];

    var create_image_container = function(icons_array) {

        var matrix =  new Array(6);
        var random_value = 0;
        var main_page_icon_matrix = $(document.createElement('div')).prependTo('#main_page_desktop').addClass('main_page_icon_matrix');
        for (var i = 0; i < 6; i++) {
            matrix[i] = new Array(24);
                     
            for (var j = 0; j < 5; j++) {
                  random_value = (Math.floor(Math.random()*24));
                  if (matrix[i][random_value] != 1) {

                      matrix[i][random_value] = 1;
                      $(document.createElement('img')).appendTo(main_page_icon_matrix)
                                                      .attr('src', icons_array[(Math.floor(Math.random() * icons_array.length))])
                                                      .css({'top'   : i * 50 + 9 + 'px',
                                                            'right' : random_value * 50 + 9 + 'px'
                                                           });
                      }

            }
        }
        
        return main_page_icon_matrix
    } 
    
    
    start_animate = function(){
        var was_called = 0;
        $('.main_page_icon_matrix').animate({'top':'+=300'},10000, 'linear',function(){
            $(this).css('top','-=300');
            if(!was_called) {
                was_called = 1;                
                create_image_container(icons);
                
                $('.main_page_icon_matrix:last').remove();
                
                start_animate();
            }
            
            });
    }
    
    create_image_container(icons);
    create_image_container(icons);
    create_image_container(icons);
    start_animate();
   
    }
}

function UrlHistoryStateInit() {

    if(typeof(window.history.pushState) === 'function') {
        $('.internal_action').click(function() {
            var self = $(this),
                urlName = self.find('.mini_name').text();

            window.history.pushState(urlName, urlName, self.attr('href'));
        })
    }
}

    //userLinksInit();

 //   uploadUserWallpaper();
    //loginToRecover();
    //slider();
    
  //  internalNavigation();
//    subInternalNavigation();
 //   messagePaginationNavigation()
 //   messageSlider();
 //   templateNotificationInit();
    
//    standardFormInit();
    //loginFormInit();
 //   experienceEducationFormInit();
//    registerAccountFormInit();
    //bind live
 
 //   actionEdit();
 //   actionDelete();
 //   stillInit();
 //   checkboxesInit();
//    actionTipsy();
//    inputTipsyInit();
 //   multiselectInit();
 //   inputScreenSettingsInit();
 //   inputDateInit();
    
 //   deleteUserPhotoInit();
  //  deleteUserWallpaperInit()
    
    
//    toggleBoxesInit();
 //   createAccountInit();
    
 //   actionPendingRequest()
//    actionAddFriendInit()
//    scrollInit()
    
  //  autosuggestContactsInit()
  //  autosuggestLocalityInit()
    
 //   ellipsisInit()
   // fixedProjectHeaderInit()
  //  noticeInit()
 //   mainPageAnimation()
    
 //   messageSearch()
  
//    UrlHistoryStateInit();

}); 
